package me.weijing.common.http;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

public class NetBroadCastReceiver extends BroadcastReceiver {

	private NetworkStateListener listener;

	public NetBroadCastReceiver(NetworkStateListener listener) {
		this.listener = listener;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		
		int type = searchCommuType(context);
		if (listener != null) {
			listener.commuTypeChange(type);
		}
	}

	/**
	 * 搜索可用的网络
	 * 
	 * @param context
	 * @return
	 */
	public int searchCommuType(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo active = manager.getActiveNetworkInfo();
		int commType = AZusNetConstant.COMMU_NULL;
		if (active != null) {
			int type = active.getType();
			if (type == ConnectivityManager.TYPE_WIFI) {
				commType = AZusNetConstant.COMMU_WIFI;
			} else if (type == ConnectivityManager.TYPE_MOBILE) {
				String extraInfo = active.getExtraInfo();
				if (!TextUtils.isEmpty(extraInfo)) {
					extraInfo = extraInfo.toLowerCase();
					if (extraInfo.equals("cmwap")) {
						commType = AZusNetConstant.COMMU_CMWAP;
					} else if (extraInfo.equals("uniwap")) {
						commType = AZusNetConstant.COMMU_UNIWAP;
					} else if (extraInfo.equals("ctwap")) {
						commType = AZusNetConstant.COMMU_CTWAP;
					} else if(extraInfo.equals("3gwap")){
						commType = AZusNetConstant.COMMU_3GWAP;
					}else if(extraInfo.equals("#777")){//电信3g手机
						commType = AZusNetConstant.COMMU_NET;
					}else{
						commType = AZusNetConstant.COMMU_NET;
					}
				}else{
					commType = AZusNetConstant.COMMU_NET;
				}
			}
		}
		return commType;
	}

	public void removeNetworkStateListener() {
		listener = null;
	}
	
	public interface NetworkStateListener {	
		public void commuTypeChange(int commuType);
	}
}
